/**
 * 
 */
package com.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.client.cache.ISpCodeManager;
import com.client.cache.PhoneNumberManager;
import com.client.cache.PhoneNumberThread;
import com.client.cache.SdkIPayOrderManager;
import com.client.cache.SdkIPayOrderStatusManager;
import com.client.cache.UserManager;
import com.client.model.ISpCodeProvince;
import com.client.model.SdkIPayOrder;
import com.client.model.SdkIniResponse;
import com.client.model.SdkPayOrderCode;
import com.client.model.User;
import com.filter.BlackListFilter;
import com.filter.SystemLimitFilter;
import com.manage.cache.AppPointOfBillingManager;
import com.manage.cache.AppSdkManager;
import com.manage.cache.ChannelAppInfoManager;
import com.manage.cache.CpAppInfoManager;
import com.manage.model.AppPointOfBilling;
import com.manage.model.AppSdk;
import com.manage.model.ChannelAppInfo;
import com.manage.model.CpAppInfo;
import com.util.Base64;
import com.util.PayErrorCode;
import com.util.PayRequestParameter;
import com.util.ProvinceUtil;
import com.util.RegionUtil;
import com.util.SyndMobileNo;
import com.util.Util;
import com.util.ZipHelper;

public class SdkPayAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	public String execute() {
		return null;
	}
	/**
	 * 
	 *opcode=5001&userid=1&imei=869717010036506&mac=68:9c:5e:30:96:81&
	 *imsi=460023865014243&simsn=8986002823118a594243&operator=46002
	 *&smsc=+8613800851503;+8613800852502&mobile=&net=wifi&
	 *appid=APQW12DSS5&chid=CH123456&
	 *package=com.example.demo&version=1.2.0.2&
	 *appflag=572998&md5=89c52ef4aa85f494a54f6a36261292e5&
	 *location=/data/app/com.example.demo-2.apk&
	 *android_id=e49629eb92a95628&board=signal77_ics2
	 *&manufacturer=alps&device=signal77_ics2&
	 *product=YOUPU U6&model=YOUPU U6
	 *&brand=alps&sdk=15&sdk_int=15&release=4.1.1&code=demo&name=示例&fee=500

	 */
	public SdkPayAction() {
		time = System.currentTimeMillis();
	}
	
	private long time;
	private String appnumber;

	public String order()
	{
		//return out(resultStr.toString().replace("&", "&amp;"));
		Map<String, String> requestMap =null;
		try {
			String str = getInputStreamAsString();
			logger.info("request thread:" + Thread.currentThread().getName() + " POST:" + str);
			requestMap = PayRequestParameter.getRequestParameter(new String(ZipHelper.unzip((Base64.decode(str, Base64.DEFAULT))),"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		SdkIniResponse inir = new SdkIniResponse();
		String errorcode = "";
		if(requestMap==null)
		{
			errorcode = PayErrorCode.RESPONSE_PARAM_ERROR;
		}else
		{
			logger.info("pay"+" "+Util.dateToString(new Date())+" pay request Parameter -- ["+requestMap.toString()+"]");
			
			//判断参数，如果参数不符合直接返回
			errorcode = PayRequestParameter.checkRequestParameter(requestMap);
		}
		if(errorcode!=null && errorcode.length()>0)
			return out(inir.generatenull(null,errorcode));
		String productid = "";
		String extchid = "";
		String cpid = "";
		//支付版本code
		String payversioncode = requestMap.get("kpay_versioncode");
		String payversionname = requestMap.get("kpay_versionname") ;
		//验证SDK版本、分配的APP等信息
		//requestMap.get("appid")  获取的是 版本number  （appversionnumber）
		ChannelAppInfo channelapp = ChannelAppInfoManager.getInstance().getChannelAppInfoByAppVersionNumber(requestMap.get("appid"),requestMap.get("chid"));

		if(channelapp==null || !channelapp.getAppstatus().equals("0"))
		{
			appnumber = requestMap.get("appid");
			CpAppInfo cpapp = CpAppInfoManager.getInstance().getCpAppInfoByAppNumber(appnumber);
			if(cpapp!=null)
			{
				if(requestMap.get("package").equals(cpapp.getApppackage().trim()))
				{
					productid = ""+cpapp.getProjectid();
					extchid = ""+cpapp.getChannelid();
					List<AppPointOfBilling> al = AppPointOfBillingManager.getInstance().getAppPointOfBillingOfAppNumber(appnumber, requestMap.get("code"));
					if(al==null || al.size()<=0)
					{
						errorcode = PayErrorCode.RESPONSE_APP_ERROR;
					}
				}else
				{
					errorcode = PayErrorCode.RESPONSE_APP_ERROR;
				}
			}else{
				errorcode = PayErrorCode.RESPONSE_APP_ERROR;
			}
		}else
		{
			appnumber = channelapp.getAppnumber();
			if(requestMap.get("package").equals(channelapp.getApppackage().trim()))
			{
				productid = ""+channelapp.getProjectid();
				extchid = ""+channelapp.getChannelid();
				cpid = ""+channelapp.getCpid();
				List<AppPointOfBilling> al = AppPointOfBillingManager.getInstance().getAppPointOfBillingOfAppNumber(appnumber, requestMap.get("code"));
				if(al==null || al.size()<=0)
				{
					errorcode = PayErrorCode.RESPONSE_APP_ERROR;
				}
			}else
			{
				errorcode = PayErrorCode.RESPONSE_APP_ERROR;
			}
		}
		if(errorcode!=null && errorcode.length()>0)
			return out(inir.generatenull(null,errorcode));
		
		if(productid.equals("") || productid.equals("0"))
			productid = "-1";
		if(extchid.equals("") || extchid.equals("0"))
			extchid = "-1";
		if(cpid.equals("") || cpid.equals("0"))
			cpid = "-1";
		
		
		if(requestMap.get("mobile") ==null || requestMap.get("mobile").length()<=0)
		{
			String number = PhoneNumberManager.getInstance().getPhoneNumberByImsi(requestMap.get("imsi"));
			if(number==null || "".equals(number))
			{
			}else
			{
				requestMap.put("mobile", number);
			}
		}else
		{
			new SyndMobileNo(requestMap.get("mobile")).start();
		}

		//生成user

		User user = new User(-1, 
				java.util.UUID.randomUUID().toString().replace("-", ""), 
				requestMap.get("mobile"), requestMap.get("imsi"), requestMap.get("imei"), 
				requestMap.get("smsc"), "", -1, Integer.parseInt(extchid), 
				Integer.parseInt(productid), "", "", -1,requestMap.get("version"),
				requestMap.get("android_id"),requestMap.get("board"),requestMap.get("manufacturer"),
				requestMap.get("device"),requestMap.get("product"),requestMap.get("model"),requestMap.get("sdk"),
				requestMap.get("sdk_int"),requestMap.get("release"),requestMap.get("simsn"),
				requestMap.get("mac"),Integer.parseInt(cpid),appnumber,requestMap.get("chid"));
		
		UserManager.getInstance().handle(user);
		
		/**
		 * 0正常下发
		 * 1 黑名单
		 * 2、超系统日月限
		 * 3、没有匹配到省份
		 * 4、没有可用代码
		 * public class PayErrorCode {
	public static final String RESPONSE_PARAM_ERROR = "110000";  //参数错误
    public static final String RESPONSE_MONEY_ERROR = "110001";  //请求金额错误
    public static final String RESPONSE_NO_CHANNEL_ERROR = "110002"; //没有部署通道
    public static final String RESPONSE_UNKNOWN_AREA_ERROR = "110003"; //省份匹配错误

    public static final String RESPONSE_APP_ERROR = "110004";         //app验证没通过
    public static final String RESPONSE_CHANNEL_ERROR = "110005";	  //匹配不到相应的通道
    public static final String RESPONSE_BLACK_USER = "110006";		  //黑名单
    public static final String RESPONSE_BLACK_USER = "110007";        //系统日月限
}
		 */
		
		//2、计费次数，是否超系统设置单手机日月限制
		if(requestMap.get("fee").equals("47"))
		{
			if(SystemLimitFilter.getInstance().isSystemLimit(user.getMobile(), user.getImsi(), user.getImei(),extchid,productid))
			{
				logger.error(Util.dateToString(new Date())+" user " + user.toLogString()+" is SystemLimitFilter");
				errorcode = PayErrorCode.RESPONSE_SYSTEM_LIMIT;
			}
		}
		//1、过滤黑名单
		if(user.getMobile()!=null && user.getMobile().length()>0)
		{
			
			if(BlackListFilter.getInstance().isBlack(user.getMobile()))
			{
				logger.error("enginname:kypay"+" "+Util.dateToString(new Date())+" user" + user.toLogString()+" is black");

				errorcode = PayErrorCode.RESPONSE_BLACK_USER;
			}
		}
		
		//4、取可用代码，返回。
		//获取支持的sdk列表,如果支持1000 则去取系统代码，
		List<AppSdk> sdklist = AppSdkManager.getInstance().getAppSdkByAppnumber(appnumber);
		List<ISpCodeProvince> reliast = new ArrayList<ISpCodeProvince>();
		List<AppSdk> resdklist = new ArrayList<AppSdk>();
		String responseStr = "";
		
		String provinceCode = ProvinceUtil.getInstance().getProvinceByName(user.getProvince());
		String regionCode = RegionUtil.getInstance().getRegionByRegionName(provinceCode, user.getRegion());
		String carrierCode = "CMCC";
		if(user.getCarrier()!=null)
		{
			if(user.getCarrier().indexOf("移动")>-1)
				carrierCode="CMCC";
			else if(user.getCarrier().indexOf("联通")>-1)
				carrierCode="UNICOM";
			else if(user.getCarrier().indexOf("电信")>-1)
				carrierCode="TELECOM";
		}
		if(errorcode.equals(""))
		{
			if(sdklist!= null &&sdklist.size()>0)
			{
				for(int i = 0;i<sdklist.size();i++)
				{
					if(sdklist.get(i).getSdkid()==1000)
					{
						reliast = ISpCodeManager.getInstance().getIProductCodeByUserSdkPay(carrierCode, provinceCode, regionCode,
								requestMap.get("mobile"),requestMap.get("imsi"),requestMap.get("net"),requestMap.get("fee"));
						break;
					}
				}
			}
			if(reliast==null || reliast.size()<=0)
			{
				resdklist = ISpCodeManager.getInstance().getAppSdk(carrierCode, provinceCode, regionCode, sdklist,requestMap.get("fee"));
			}
			SdkIPayOrder order = new SdkIPayOrder(user.getId(), user.getMobile(), carrierCode, provinceCode, regionCode,
					requestMap.get("fee"), user.getChannelId(), user.getProjectId(),
					new Date(), new Date()
					,Integer.parseInt(cpid),appnumber
					,requestMap.get("code"),requestMap.get("name")
					,requestMap.get("chid"),requestMap.get("fee"),"0",user.getImsi());
			if((reliast==null||reliast.size()<=0) && (resdklist==null||resdklist.size()<=0))
			{
				errorcode = PayErrorCode.RESPONSE_NO_PAY;
			}
			if(reliast!=null && reliast.size()>0)
			{
				List<SdkPayOrderCode> paycode= new ArrayList<SdkPayOrderCode>();
				for(int g=0;g<reliast.size();g++)
				{
					ISpCodeProvince icp = reliast.get(g);
					SdkPayOrderCode soc = new SdkPayOrderCode();
					soc.setCodeType(icp.getCodeType());
					soc.setOrderid(order.getOrderId());
					soc.setOrderType(icp.getOrderType());
					soc.setSpCodeId(icp.getId());
					soc.setSpId(icp.getSpId());
					int item = 0;
					if(icp.getFeeValue().equals(order.getRequestfee()))
					{
						item = 1;
					}
					else
					{
						item = (Integer.parseInt(order.getRequestfee())/Integer.parseInt(icp.getFeeValue()));
					}
					soc.setItem(item);
					paycode.add(soc);
				}
				order.setCodelist(paycode);
			}
			responseStr = inir.generate(order, errorcode, reliast, resdklist,payversioncode,payversionname,requestMap.get("appid"),requestMap.get("code"));
			SdkIPayOrderManager.getInstance().handle(order);
		}
		else
		{
			SdkIPayOrder order = new SdkIPayOrder(user.getId(), user.getMobile(), carrierCode, provinceCode, regionCode,
					"0", user.getChannelId(), user.getProjectId(),
					new Date(), new Date()
					,Integer.parseInt(cpid),appnumber
					,requestMap.get("code"),requestMap.get("name")
					,requestMap.get("chid"),requestMap.get("fee"),"0",user.getImsi());
			responseStr = inir.generatenull(order,errorcode);
			SdkIPayOrderManager.getInstance().handle(order);
		}
		logger.info("enginname:kypay"+" "+Util.dateToString(new Date())+" ["+requestMap.toString()+"] pay request Parameter -- result:"+errorcode);
		return out(responseStr);
	}

	public String r()
	{
		//v={version}&svid={serviceid}&exid={extchid}&pid={productid}&cct=1&mo={number}
		Map<String, String> requestMap = null;
		try {
			String str = getInputStreamAsString();
			requestMap = PayRequestParameter.getRequestParameter(new String(ZipHelper.unzip((Base64.decode(str, Base64.DEFAULT))),"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		//String orderId,String suborderId,int report, Date reportTime
		if(requestMap!=null)
		{
			logger.info("payreport"+" "+Util.dateToString(new Date())+" payreport request Parameter -- ["+requestMap.toString()+"]");
			SdkIPayOrder order = new SdkIPayOrder(requestMap.get("orderid")
					,""
					, Integer.parseInt(requestMap.get("report")), new Date(),requestMap.get("amount"),requestMap.get("provider"));
			SdkIPayOrderStatusManager.getInstance().handle(order);
		}
		String responseStr = "ok";
		return out(responseStr);
	}
	
	private String out(String rsp)
	{
		try {
			//rsp = Base64.encode(rsp.getBytes("UTF-8"));
			rsp = rsp.replace("${host}", request.getServerName()+":"+request.getServerPort());
			String s =  new String(Base64.encode(
					ZipHelper.zip(rsp.getBytes()), Base64.DEFAULT),"utf-8");
			System.out.println(s);
			setContentLength(s.getBytes("utf-8").length);
			setContentType("text/plain;charset=utf-8");
			PrintWriter pw = getResponse().getWriter();
			pw.write(s);
			pw.flush();
			pw.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		logger.info("thread: " + Thread.currentThread().getName() + ";cost: " + (System.currentTimeMillis() - time) + ";response:" + rsp.replace("\r", "\\r").replace("\n", "\\n"));
		return null;
	}
	public String imsi()
	{
		String mobile = getParameter("mobile");
		String imsi = getParameter("imsi");
		if(mobile!=null && imsi!=null && mobile.length()>0 && imsi.length()>0)
		{
			if(mobile.indexOf("+86")>-1)
				mobile = mobile.replace("+86", "");
			if(mobile.startsWith("86"))
			{
				mobile = mobile.substring(2,mobile.length());
			}
			new PhoneNumberThread(mobile, imsi).start();
			
		}
		String responseStr = "ok";
		return out(responseStr);
	}
	
	
}
